const OSS = require('ali-oss')
const fs = require('fs')
const path = require('path')

const ossConfig = require('./oss.config.js')
const localPath = 'dist/js'
const remotePath = 'workflow/formBuilder/'

async function put (filename, filePath) {
  const client = new OSS({...ossConfig})
  try {
    let result = await client.put(remotePath + filename, filePath)
    if (result.res.status == 200) {
      console.log(`${filename} upload to oss`)
    }
  } catch (e) {
    throw new Error(e)
  }
}

const localPathExist = function(){
  const localAbsPath = path.join(__dirname, localPath)
  // 先判断是否存在dist目录
  fs.exists(localAbsPath, (exist) => {
    if (!exist) {
      throw new Error("the 'dist' folder was not found")
    }
  })

  fs.readdir(localAbsPath, (err, fileList) => {
    if(err){
      throw new Error(err)
    } else {
      fileList.forEach((filename) => {
        const filePath = path.join(localAbsPath, filename)
        put(filename, filePath)
      })
    }
  })
}

localPathExist()
